const express = require("express");
const db = require("./../libs/DBhelper");
const fs = require("fs");
const path = require("path");
const moment = require("moment");
let apiRouter = express.Router({
    // strict: true //对路径严格
});
// 登录
apiRouter.post("/login", function (request, response, next) {
    let parmas = [
        request.body.utel,
        request.body.upwd
    ]

    let sql = "SELECT `uid`,`utel`,`utype` FROM `userinfo` WHERE ustatus=1 AND	utel=? AND upwd=?;"

    db.exec(sql, parmas, (err, result) => {
        if (!err && result.length >= 1) {
            //把当前登录者的信息保存到session
            request.session["userInfo"] = Object.assign({}, result);
            response.json({
                msg: "登陆成功",
                data: result,
                status: 1
            })
        } else {
            response.json({
                msg: "登陆失败",
                status: -1,
                err
            })
        }
    })
});
// 注册
apiRouter.post("/reg", function (request, response, next) {
    let parmas = [
        request.body.utel,
        request.body.upwd
    ];
    console.log(parmas);
    let sql = "INSERT INTO `userinfo` (`utel`,`upwd`) VALUES (?,?);";
    db.exec(sql, parmas, function (err, result) {
        if (err) {
            response.json({
                msg: "注册失败",
                status: -3,
                err
            });
            return;
        }
        if (result.affectedRows >= 1) {
            response.json({
                msg: "注册成功",
                status: 1
            })
        } else {
            response.json({
                msg: "注册失败",
                status: -1
            })
        }
    });
});
// 返回数据
apiRouter.get("/goodslist", (request, response, next) => {
    var resJson = JSON.parse(fs.readFileSync("./data/list.json").toString());
    response.json(resJson);
})
// 商品详情
apiRouter.get("/goodsById/:pid", (request, response, next) => {
    let pid = request.params.pid;

    var resArr = JSON.parse(fs.readFileSync("../data/list.json").toString());
    var resList = resArr.filter((el) => {
        return el.pid == pid;
    })
    if (resList.length >= 1) {
        response.json({
            msg: "success",
            status: 1,
            data: resList[0]
        })
    } else {
        response.json({
            msg: "fail",
            status: -1,
            data: null
        })
    }
})
// 加入购物车
apiRouter.post("/addCart", async (request, response, next) => {
    var paramsQuery = [
        request.body.uid,//购买者
        request.body.pid,//产品编号
        request.body.psize,//规则
        request.body.pname,//产品名称
        request.body.pprice,//产品价格
        request.body.pnum//数量
    ]

    var sql = "SELECT * FROM `cart` WHERE `u_status`=1 AND `u_complete`=1 AND `u_id`=? AND `p_id`=? AND p_size=?;";
    var res = await db.execAsync(sql, paramsQuery);
    if (res.length >= 1) {
        // 已经购买，修改数量
        let paramsUpdata = [
            request.body.pnum,//数量
            request.body.uid,//购买者
            request.body.pid,//产品编号
            request.body.psize//规格
        ]

        var updateSql = "UPDATE cart SET p_num=p_num+?,u_total=p_num*`p_size` WHERE u_status=1 AND u_complete = 1 AND u_id=? AND p_id=? AND p_size=?;";

        var res = await db.execAsync(updateSql, paramsUpdata);
        if (res.affectedRows >= 1) {
            response.json({
                msg: "加入购物车成功(update)",
                status: 1
            })
        } else {
            response.json({
                msg: "加入购物车失败",
                status: -1
            })
        }
    } else {
        //还没有购买，数据库没有记录
        var paramsInsert = [
            request.body.pid,//产品编号
            request.body.pname,//产品名称
            request.body.pprice,//产品价格
            request.body.psize,//规格
            request.body.pnum,//数量
            request.body.uid,//购买者
            request.body.pnum * request.body.pprice,
            moment().format("YYYY-MM-DD HH:mm:ss"),
            request.body.pphoto//商品图片
        ];
        var insertSql = "INSERT INTO `cart`(`p_id`,`p_name`,`p_price`,`p_size`,`p_num`,`u_id`,`u_total`,`u_time`,`pphoto`) VALUES (?,?,?,?,?,?,?,?,?);";

        var res = await db.execAsync(insertSql, paramsInsert);
        if (res.affectedRows >= 1) {
            response.json({
                msg: "加入购物车成功(insert)",
                status: 1
            })
        } else {
            response.json({
                msg: "加入购物车失败(insert)",
                status: -1
            })
        }
    }
})
// 购物车
apiRouter.get("/carts", async (request, response, next) => {
    let params = [
        request.query.uid
    ]
    let query = "SELECT *FROM `cart` WHERE u_status=1 AND u_complete=1 AND u_id=?";
    var res = await db.execAsync(query, params);
    response.json({
        msg: res.length >= 1 ? "查询成功" : "查询失败",
        data: res
    });
})
//修改数量
apiRouter.post("/modify", async (request, response, next) => {
    let params = [
        request.body.pnum,
        request.body.cid
    ]
    let sql = "UPDATE cart SET p_num=? ,u_total=p_num* p_price  WHERE c_id=? AND  u_status=1 AND u_complete=1";
    var res = await db.execAsync(sql, params);

    response.json({
        msg: res.affectedRows >= 1 ? "修改成功" : "修改失败",
        status: res.affectedRows >= 1 ? 1 : -1
    });
})
// 删除
apiRouter.post("/delete", async (request, response, next) => {
    let params = [
        request.body.cid
    ];
    let sql = "UPDATE cart SET u_status=0 WHERE c_id=? AND  u_status=1 AND u_complete=1";
    var res = await db.execAsync(sql, params);
     
    response.json({
        msg: res.affectedRows >= 1 ? "删除成功" : "删除失败",
        status: res.affectedRows >= 1 ? 1 : -1,
    });
})
// 退出
apiRouter.get("/quit", (request, response, next) => {
    request.session["userInfo"] = null;
    response.clearCookie("uname");
    response.json({
        msg: "退出成功",
        status: 1
    });
});
module.exports = apiRouter;